// 定义二叉树的节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    // 判断是否存在从根节点到叶子节点的路径，其路径和为 targetSum
    public boolean hasPathSum(TreeNode root, int targetSum) {
        // 如果根节点为空，直接返回 false
        if (root == null) {
            return false;
        }

        // 如果当前节点是叶子节点，并且路径和等于目标和
        if (root.left == null && root.right == null) {
            return root.val == targetSum;
        }

        // 递归检查左右子树，更新目标和
        int remainingSum = targetSum - root.val;
        return hasPathSum(root.left, remainingSum) || hasPathSum(root.right, remainingSum);
    }

    // 主函数来测试实现
    public static void main(String[] args) {
        // 构建示例二叉树
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right.right.right = new TreeNode(1);

        // 目标和
        int targetSum = 22;

        // 创建 Solution 对象并调用 hasPathSum 方法
        Solution solution = new Solution();
        boolean result = solution.hasPathSum(root, targetSum);

        // 打印结果
        System.out.println("是否存在路径和等于 " + targetSum + " ：" + result);
    }
}
